package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.review

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

class ReviewGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<ReviewGhanaResult>()
    val pageDetailResult: LiveData<ReviewGhanaResult> = _pageDetailResult

    private val _walletResult = MutableLiveData<ReviewGhanaWalletResult>()
    val walletResult: LiveData<ReviewGhanaWalletResult> = _walletResult

    private val _commendProductsResult = MutableLiveData<ReviewGhanaCommendProductsResult>()
    val commendProductsResult: LiveData<ReviewGhanaCommendProductsResult> = _commendProductsResult

    private val _reviewDialogResult = MutableLiveData<ReviewGhanaReviewDialogResult>()
    val reviewDialogResult: LiveData<ReviewGhanaReviewDialogResult> = _reviewDialogResult


    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "WvSc3ghpalrgbjmUXBKvvg"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                // 去掉无效0
                val amount = obj.optString("amount")
                val amountString = BigDecimal(amount).stripTrailingZeros().toPlainString()
                obj.put("amount", amountString)

                val currency = obj.optString("currency")
                val amountFormat = "$amountString $currency"
                obj.put("amountFormat", amountFormat)

                val days = obj.optString("days")
                obj.put("daysFormat", "$days days")

                _pageDetailResult.value = ReviewGhanaResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _pageDetailResult.value = ReviewGhanaResult(error = errMsg)
            }
        })

        // 银行卡列表
        val bankcardAction = hashMapOf<String, Any>().createApiAction()
        bankcardAction["path"] = "U5nlZIAER9LEMTlxGIBPw"
        context.doPostRequest(bankcardAction, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                val obj = jsonObject.optJSONArray("obj") ?: JSONArray()
                var defaultCard: JSONObject? = null
                for (index in 0 until obj.length()) {
                    val item = obj[index] as JSONObject
                    if (item.optString("isDef", "NO") == "YES") {
                        defaultCard = JSONObject()
                        defaultCard.put("walletLogo", item.optString("logo"))
                        defaultCard.put("walletType", item.optString("name"))
                        defaultCard.put("walletMobile", item.optString("account"))
                    }
                }
                if (defaultCard != null) {
                    _walletResult.value = ReviewGhanaWalletResult(success = defaultCard)
                } else {
                    _walletResult.value = ReviewGhanaWalletResult(error = "Wallet list is null")
                }
            }

            override fun onApiError(code: String, errMsg: String) {
                _walletResult.value = ReviewGhanaWalletResult(error = errMsg)
            }
        })

    }

    /** 获取推荐产品接口 */
    fun commendProducts() {
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "na7K1WhPIBpMqSF635Spgg"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val dcProductList = obj.optJSONArray("dcProductList") ?: JSONArray()
                val list = mutableListOf<JSONObject>()
                for (index in 0 until dcProductList.length()) {
                    val item = dcProductList[index] as JSONObject
                    list.add(item)
                }
                _commendProductsResult.value =
                    ReviewGhanaCommendProductsResult(success = list)
            }

            override fun onApiError(code: String, errMsg: String) {
                _commendProductsResult.value =
                    ReviewGhanaCommendProductsResult(error = errMsg)
            }
        })
    }

    /** 获取评价框配置接口 */
    fun reviewDialog() {
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "x8CIlIS4cYCKGUJZ2lpqEg"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val activeWindow = obj.optJSONObject("activeWindow") ?: JSONObject()
                val normalWindow = obj.optJSONObject("normalWindow") ?: JSONObject()

                val activeSwitch = activeWindow.optString("switch", "NO")
                val activeContent = activeWindow.optString("content")
                val activeNum = activeWindow.optString("num", "3").toInt()

                val normalSwitch = normalWindow.optString("switch", "NO")
                val normalContent = normalWindow.optString("content")
                val normalNum = normalWindow.optString("num", "3").toInt()

                // 已展示次数
                val didShowCount = ProjectApplication.reviewDialogAction(isGet = true)

                if (activeSwitch == "YES") {
                    if (activeNum > didShowCount) {
                        _reviewDialogResult.value =
                            ReviewGhanaReviewDialogResult(boldDialog = activeContent)
                        return
                    }
                }

                if (normalSwitch == "YES") {
                    if (normalNum > didShowCount) {
                        _reviewDialogResult.value =
                            ReviewGhanaReviewDialogResult(normalDialog = normalContent)
                        return
                    }
                }

                _reviewDialogResult.value = ReviewGhanaReviewDialogResult()
            }

            override fun onApiError(code: String, errMsg: String) {
                _reviewDialogResult.value =
                    ReviewGhanaReviewDialogResult(error = errMsg)
            }
        })
    }
}